package com.eric.enderslastgame.threads;

import java.util.ArrayList;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

import com.eric.enderslastgame.Bugger;
import com.eric.enderslastgame.EndersGamePanel;

/*
 * Moves Buggers and removes the ones that are not visible (out of the screen)
 */

public class GameThread extends Thread {

	private static final String TAG = GameThread.class.getSimpleName();

	// Surface holder that can access the physical surface
	private SurfaceHolder surfaceHolder;
	// The actual view that handles inputs
	// and draws to the surface
	private EndersGamePanel gamePanel;

	public GameThread(SurfaceHolder surfaceHolder, EndersGamePanel gamePanel) {
		super();
		this.surfaceHolder = surfaceHolder;
		this.gamePanel = gamePanel;
	}

	@Override
	public void run() {
		Log.d(TAG, "Starting game thread");
		while (EndersGamePanel.inGame) {
			// Log.d(TAG, "Going through Bugger removal process");
			for (int i = 0; i < gamePanel.buggers.size(); i++) {
				ArrayList<Bugger> buggerList = gamePanel.buggers.get(i); // Get
																			// the
																			// current
																			// ArrayList<Bugger>
				gamePanel.checkCollisions(gamePanel.humans.get(i), buggerList);
				for (int k = 0; k < buggerList.size(); k++) {
					Bugger bugger = buggerList.get(k);
					if (bugger.isVisible()) {
						bugger.move();
//						Log.d(TAG, "Moved Bugger");
					} else {
						buggerList.remove(k);
						EndersGamePanel.dodgedCounter += 1;
//						Log.d(TAG, "Bugger removed because not visible");
					}
				}
			}

			Canvas canvas;

			canvas = null;
			// try locking the canvas for exclusive pixel editing
			// in the surface
			try {
				canvas = this.surfaceHolder.lockCanvas();
				synchronized (surfaceHolder) {
					// render state to the screen
					// draws the canvas on the panel
					gamePanel.render(canvas);
				}
			} finally {
				// in case of an exception the surface is not left in
				// an inconsistent state
				if (canvas != null) {
					surfaceHolder.unlockCanvasAndPost(canvas);
				}
			}

			
			try {
				sleep(EndersGamePanel.SLEEP_TIME_GAME_ACTIONS);
			} catch (InterruptedException e) {
				Log.d(TAG, "Problems sleeping the thread");
			}
		}
	}
}
